﻿using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System.Linq;

namespace Lapis.Share
{
    /// <summary>
    /// 视图模型基类
    /// </summary>
    public abstract class BaseViewModel : BindableBase
    {
        private DelegateCommand _loadCommand;
        protected IEventAggregator EventAggregator { get; } //事件聚合器
        protected IRegionManager RegionManager { get; } // 区域管理器
        public DelegateCommand LoadCommand => _loadCommand ??= new(OnLoad); //界面加载命令

        public BaseViewModel()
        {
            RegionManager = ContainerLocator.Current.Resolve<IRegionManager>();
            EventAggregator = ContainerLocator.Current.Resolve<IEventAggregator>();
        }

        /// <summary>
        /// 界面加载时，由Loaded事件触发
        /// </summary>
        protected virtual void OnLoad()
        {
        }

        /// <summary>
        /// 根据区域名称查找视图
        /// </summary>
        /// <param name="regionName">区域名称</param>
        protected TView TryFindView<TView>(string regionName) where TView : class
        {
            return RegionManager.Regions[regionName].Views
                     .Where(v => v.GetType() == typeof(TView))
                     .FirstOrDefault() as TView;
        }
    }
}